﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 线程
{
    public partial class Form1 : Form
    {
        public delegate void WriteTextDelegate(char ch);
        public WriteTextDelegate writeText;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string text = textBox1.Text;
            Thread thread = new Thread(() => CopyText(text));
            thread.Start();
        }

        private void CopyText(string text)
        {
            if (checkBox1.Checked)
            {
                foreach (char ch in text)
                {
                    AppendCharSafe(richTextBox1, ch);
                }
            }
            Thread.Sleep(1000);
            if (checkBox2.Checked)
            {
                foreach (char ch in text)
                {
                    AppendCharSafe(richTextBox2, ch);
                }
            }
        }

        private void AppendCharSafe(RichTextBox richTextBox, char ch)
        {
            if (richTextBox.InvokeRequired)
            {
                richTextBox.Invoke(new MethodInvoker(delegate
                {
                    richTextBox.AppendText(ch.ToString() + Environment.NewLine);
                }));
            }
            else
            {
                richTextBox.AppendText(ch.ToString() + Environment.NewLine);
            }
        }
    }
}